package com.xinchao.api;

import com.xinchao.constant.AdvertisementConstant;
import com.xinchao.constant.RequestParameterConstant;
import com.xinchao.constant.ResponseConstant;
import com.xinchao.exception.ControllerException;
import com.xinchao.exception.ServiceException;
import com.xinchao.model.Advertiser;
import com.xinchao.model.sys.JsonResponse;
import com.xinchao.service.AdvertiserService;
import com.xinchao.util.JWTUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author dxy
 * @date 2018/11/8 16:24
 */
@Controller
@RequestMapping(value = "/web")
public class WebController {
	private static Logger logger = LoggerFactory.getLogger(WebController.class);

	@Autowired
	private AdvertiserService advertiserService;

	/**
	 * 登录（小程序登录，是用的广告主表frp_advertiser中的账号、密码）
	 */
	@ResponseBody
	@RequestMapping(value = "/login")
	public Object login(String userName, String password, HttpServletResponse response) {
		//验证用户名
		if (StringUtils.isBlank(userName)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "用户名不能为空");
		}
		//验证密码
		if (StringUtils.isBlank(password)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "密码不能为空");
		}
		try {
			Advertiser advertiser = advertiserService.getAdvertiserByUserName(userName);
			if (advertiser == null) {
				return new JsonResponse(ResponseConstant.CODE_FAIL, "用户名或密码不正确");
			}
			//验证密码是否正确
			String md5HexPassword = DigestUtils.md5Hex(password);
			if (!md5HexPassword.equals(advertiser.getPassword())) {
				return new JsonResponse(ResponseConstant.CODE_FAIL, "用户名或密码不正确");
			}
		} catch (ServiceException e) {
			String message = e.getMessage();
			logger.error("WebController login 登录失败：" + message);
			return new ControllerException(message);
		}
		//产生token
		String token = JWTUtils.generateJWTToken(AdvertisementConstant.JWT_TIME_OUT_TIME, userName);
		//返回token
		Map<String, String> paramMap = new HashMap<>();
		paramMap.put(RequestParameterConstant.TOKEN, token);
		paramMap.put(RequestParameterConstant.USER_NAME, userName);
		return paramMap;
	}

}
